import React,{useState,useRef,useEffect} from 'react'
import { useSelector,useDispatch } from 'react-redux'
import classNames from 'classnames'
import { changeStatus, delTodo, selectAll } from '../../store/actions/todo'


export default function TodoMain() {
  // 准备currentId
  const [currentId, setCurrentId] = useState('')
  // 创建ref引用
  const inputRef = useRef()
  const list = useSelector((state) => state.todo)
  const dispatch =  useDispatch()
  // 删除
  const handleDel = (id) =>{
    dispatch(delTodo(id))
  }
  // 修改状态
  const handleChangeStatus = (id) =>{
    dispatch(changeStatus(id))
  }
  // !确定全选的状态，根据所有的单选的状态来确定
  const isCheckAll = list.every((item) => item.done)
  // !全选操作
  const handleChangeAll = () => dispatch(selectAll(!isCheckAll))
// 双击显示对话框
 const handleDBLLable =(id) =>{
    setCurrentId(id)
  }
  useEffect(()=>{
    inputRef.current.focus()
  },[currentId])

  return (
    <section className='main'>
      <input id='toggle-all' 
      className='toggle-all'
       type='checkbox' 
       checked={isCheckAll}
       onChange={handleChangeAll}
       />
      <label htmlFor='toggle-all'>Mark all as complete</label>
        {/* // #2. 用 currentID 和 item.id 进行比较，如果是 true 就应用 editing class */}
      <ul className='todo-list'>
        {list.map((item) => (
          <li
            key={item.id}
            className={classNames({
              completed: item.done,
              editing:item.id === currentId
            })}
          >
            <div className='view'>
              <input
                className='toggle'
                type='checkbox'
                checked={item.done}
                onChange={() =>  handleChangeStatus(item.id)}
              />
              <label onDoubleClick={() =>handleDBLLable(item.id) }>{item.name}</label>
              <button className='destroy' onClick={() => handleDel(item.id)}></button>
            </div>
              {/* #2. ref 引用和 input 编辑框进行绑定 */}
            <input
              className='edit'
              value={item.name}
              onChange={() => {}}
              ref={inputRef}
            />
          </li>
        ))}
      </ul>
    </section>
  )
}